package com.blb.servlet;

import com.mysql.cj.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * 从请求中获取请求路径，从请求路径中取出要调用的方法
 * 反射调用该方法即可
 */
public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        String methodStr = uri.substring(uri.lastIndexOf("/") +1);
        try {
            Method method = this.getClass().getDeclaredMethod(methodStr, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this,req,resp);
        } catch (Exception e) {
            resp.getWriter().write("找不到该方法");
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取页数
     * @param req
     * @return
     */
    protected int getPage(HttpServletRequest req){
        String page = req.getParameter("page");

        if (StringUtils.isNullOrEmpty(page)){
            page="1";
        }
        return Integer.parseInt(page);
    }

    /**
     * 获取每页多少条
     * @param req
     * @return
     */
    protected int getSize(HttpServletRequest req){
        String size = req.getParameter("size");
        if (StringUtils.isNullOrEmpty(size)){
            size="5";
        }
        return Integer.parseInt(size);
    }






}
